package com.cuteboy.util;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class XmlBuilderUtil {
    /**
     * 将xml文件转为制定的pojo对象
     * @param clazz 将要转成的对象类型
     * @param xmlStr 数据字符串
     * @return
     */
    public static Object xmlStrToObject(Class<?> clazz,String xmlStr) throws IOException {
        Object xmlObject = null;
        Reader reader = null;
        try {
            reader = new StringReader(xmlStr);
            //提供了 xml 转为对象的接口
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            xmlObject = unmarshaller.unmarshal(reader);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        if (reader != null){
            reader.close();
        }
        return xmlObject;
    }
}
